//
//  EMConversationCell.swift
//  easeIM-swift
//
//  Created by yangjian on 2022/7/13.
//

import UIKit
import RxSwift
import RxCocoa
import Kingfisher
import HyphenateChat


class EMConversationCell: UITableViewCell {
    var reusebag = DisposeBag()
//    public typealias Delegate = EMConversationCellDelegate
//    public weak var delegate : EMConversationCellDelegate?
    let headImageView = UIImageView()
    let nameLabel = UILabel()
    let lastMessageLabel = UILabel()
    let timeLabel = UILabel()
    
    
    let badgeBgView = UIView()
    let badgeLabel = UILabel()
    let silentBadgeView = UIView()

    override func prepareForReuse() {
        super.prepareForReuse()
        reusebag = DisposeBag()
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.config()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func config(){
        self.contentView.addSubview(headImageView)
        self.contentView.addSubview(nameLabel)
        self.contentView.addSubview(lastMessageLabel)
        self.contentView.addSubview(timeLabel)
                
        headImageView.addSubview(badgeBgView)
        badgeBgView.addSubview(badgeLabel)

        headImageView.addSubview(silentBadgeView)
        
        headImageView.snp.makeConstraints { make in
            make.centerY.equalTo(self.contentView)
            make.left.equalTo(20)
            make.width.equalTo(40)
            make.height.equalTo(40)
        }
        
        badgeBgView.snp.makeConstraints { make in
            make.centerY.equalTo(headImageView.snp.top)
            make.width.greaterThanOrEqualTo(20)
            make.height.equalTo(20)
            make.centerX.equalTo(headImageView.snp.right)
        }
        
        badgeLabel.snp.makeConstraints { make in
            make.centerY.equalTo(badgeBgView)
            make.left.equalTo(badgeBgView).offset(5)
            make.right.equalTo(badgeBgView).offset(-5)
        }
        
        silentBadgeView.snp.makeConstraints { make in
            make.centerX.equalTo(headImageView.snp.right)
            make.centerY.equalTo(headImageView.snp.top)
            make.width.height.greaterThanOrEqualTo(6)
        }

        
        nameLabel.snp.makeConstraints { make in
            make.centerY.equalTo(self.headImageView).offset(-15)
            make.left.equalTo(self.headImageView.snp.right).offset(10)
        }
        lastMessageLabel.snp.makeConstraints { make in
            make.centerY.equalTo(self.headImageView).offset(15)
            make.left.equalTo(self.headImageView.snp.right).offset(10)
            make.right.equalTo(-20)
        }
        timeLabel.snp.makeConstraints { make in
            make.top.equalTo(4)
            make.right.equalTo(-20)
        }
        
        headImageView.isUserInteractionEnabled = true
        headImageView.backgroundColor = UIColor.orange

        badgeBgView.backgroundColor = UIColor.red
        badgeBgView.layer.masksToBounds = true
        badgeBgView.layer.cornerRadius = 9
        badgeBgView.isHidden = true

        silentBadgeView.backgroundColor = UIColor.red
        silentBadgeView.layer.masksToBounds = true
        silentBadgeView.layer.cornerRadius = 3
        silentBadgeView.isHidden = true

        
        badgeLabel.textColor = UIColor.white
        badgeLabel.font = UIFont.systemFont(ofSize: 13)
        badgeLabel.textAlignment = .center
        

        
    }
    
    func bindFromModel(cellModel : EMConversationCellModel){
        nameLabel.text  = cellModel.id
        lastMessageLabel.text = cellModel.newMessageContent()
        if cellModel.chatType == .singleChat {
            cellModel.rx_userInfo.subscribe(onNext: {[unowned self] userInfo in
                var haveUserInfo = false
                if let username = userInfo.userId {
                    if username.count > 0 {
                        haveUserInfo = true
                    }
                }
                if haveUserInfo {
                    if userInfo.nickname?.count ?? 0 > 0 {
                        self.nameLabel.text = userInfo.nickname
                    }else{
                        self.nameLabel.text = cellModel.id
                    }
                    self.headImageView.image = UIImage(named: cellModel.headImageName);
                    if let url = URL(string: userInfo.avatarUrl ?? "") {
//                        self.headImageView.kf.setImage(with: .network(ImageResource(downloadURL: url) as! Resource))
                    }
                }else{
                    self.nameLabel.text = cellModel.id
                    self.headImageView.image = UIImage(named: cellModel.headImageName);
                }
            }).disposed(by: reusebag)
        }else{
            self.nameLabel.text = cellModel.id
            self.headImageView.image = UIImage(named: cellModel.headImageName);
        }
        
        if let conversation = cellModel.conversation {
            //判断是否免打扰
            var isSilent = false
            if cellModel.chatType == .singleChat{
                let noPushUsers = EMClient.shared().pushManager?.noPushUIds as! [String]
    //            let noPushGroups = EMClient.shared().pushManager?.noPushGroups as! [String]
                //判断是否免打扰
                if noPushUsers.contains(conversation.conversationId) {
                    isSilent = true
                }
            }else if cellModel.chatType == .groupChat {
//                let noPushUsers = EMClient.shared().pushManager?.noPushUIds as! [String]
                let noPushGroups = EMClient.shared().pushManager?.noPushGroups as! [String]
                //判断是否免打扰
                if noPushGroups.contains(conversation.conversationId) {
                    isSilent = true
                }
            }else{
                isSilent = true
            }
            if isSilent {
                silentBadgeView.isHidden = false
                badgeBgView.isHidden = true
            }else{
                let unreadCount = conversation.unreadMessagesCount
                if unreadCount == 0 {
                    badgeBgView.isHidden = true
                    badgeLabel.text = "";
                }else if unreadCount > 99 {
                    badgeBgView.isHidden = false
                    badgeLabel.text = "99+";
                }else{
                    badgeBgView.isHidden = false
                    badgeLabel.text = "\(unreadCount)"
                }
            }
        }
    }
}

//extension EMConversationCell {
//    @objc func headImageViewDidClick(gusture : UITapGestureRecognizer){
//        self.delegate?.headImageViewDidClick(cell: self, indexPath: IndexPath.init(), model: EMConversationCellModel.init(id: "", chatType: IMChatType.singleChat))
//    }
//    @objc func headImageViewDidDoubleClick(gusture : UITapGestureRecognizer){
//        self.delegate?.headImageViewDidClick(cell: self, indexPath: IndexPath.init(), model: EMConversationCellModel.init(id: "", chatType: IMChatType.singleChat))
//    }
//
//}

//@objc protocol EMConversationCellDelegate : AnyObject {
//    func headImageViewDidClick(cell:UITableViewCell , indexPath:IndexPath , model : EMConversationCellModel) -> Void;
//    func headImageViewDidDoubleClick(cell:UITableViewCell , indexPath:IndexPath , model : EMConversationCellModel) -> Void;
//}
//
//
//
//class RxEMConversationCellProtocolProxy : DelegateProxy<EMConversationCell,EMConversationCellDelegate>,DelegateProxyType,EMConversationCellDelegate{
//    func headImageViewDidClick(cell: UITableViewCell, indexPath: IndexPath, model: EMConversationCellModel) {
//        _forwardToDelegate?.headImageViewDidClick(cell: cell, indexPath: indexPath, model: model)
//    }
//
//    func headImageViewDidDoubleClick(cell: UITableViewCell, indexPath: IndexPath, model: EMConversationCellModel) {
//        _forwardToDelegate?.headImageViewDidDoubleClick(cell: cell, indexPath: indexPath, model: model)
//    }
//
//    static func registerKnownImplementations() {
//        self.register { obj in
//            RxEMConversationCellProtocolProxy(cell: obj)
//        }
//    }
//
//    static func currentDelegate(for object: EMConversationCell) -> EMConversationCellDelegate? {
//        return object.delegate
//    }
//
//    static func setCurrentDelegate(_ delegate: EMConversationCellDelegate?, to object: EMConversationCell) {
//        object.delegate = delegate
//    }
//
//    public init(cell : EMConversationCell) {
//        super.init(parentObject: cell, delegateProxy: RxEMConversationCellProtocolProxy.self)
//    }
//}


